<?php

namespace App\Services;

use App\Models\UserAiThread;
use OpenAI\Laravel\Facades\OpenAI;

class UserService
{
    public function getOrCreateThread($userId)
    {
        $model = UserAiThread::where('b24_user_id', $userId)->first();

        if ($model) {
            return $model->thread;
        } else {
            $thread = OpenAI::threads()->create([]);
            $threadId = $thread->id;

            if ($userId) {
                UserAiThread::create([
                    'thread' => $threadId,
                    'b24_user_id' => $userId
                ]);
            }

            return $threadId;
        }
    }

    public function createUserAiThread($userId, $threadId)
    {
        UserAiThread::create([
            'thread' => $threadId,
            'b24_user_id' => $userId
        ]);
    }
}
